import type { ApiResponse, DatabaseQuery, Interceptor, QueryResult } from '@/types/ollama'

export class DatabaseService {
  private interceptors: Interceptor<DatabaseQuery, QueryResult>[] = []

  constructor(private readonly mcpClient: any) {
    // 初始化 MCP 客户端
  }

  // 添加拦截器
  addInterceptor(interceptor: Interceptor<DatabaseQuery, QueryResult>) {
    this.interceptors.push(interceptor)
  }

  // 执行查询
  async query<T = any>(query: DatabaseQuery): Promise<ApiResponse<QueryResult<T>>> {
    try {
      // 执行请求拦截器
      const interceptedQuery = await this.executeRequestInterceptors(query)

      // 执行查询
      const result = await this.mcpClient.query(interceptedQuery.query, interceptedQuery.params)

      // 执行响应拦截器
      const interceptedResult = await this.executeResponseInterceptors(result)

      return {
        code: 200,
        message: 'Success',
        data: interceptedResult,
        timestamp: Date.now(),
      }
    } catch (error) {
      // 执行错误拦截器
      const interceptedError = await this.executeErrorInterceptors(error as Error)

      return {
        code: 500,
        message: interceptedError.message,
        data: { rows: [], rowCount: 0, fields: [] },
        timestamp: Date.now(),
      }
    }
  }

  // 移除拦截器
  removeInterceptor(interceptor: Interceptor<DatabaseQuery, QueryResult>) {
    const index = this.interceptors.indexOf(interceptor)
    if (index !== -1) {
      this.interceptors.splice(index, 1)
    }
  }

  // 执行事务
  async transaction<T = any>(queries: DatabaseQuery[]): Promise<ApiResponse<QueryResult<T>[]>> {
    try {
      const results: QueryResult<T>[] = []

      // 开始事务
      await this.mcpClient.query('BEGIN')

      try {
        // 执行所有查询
        for (const query of queries) {
          const interceptedQuery = await this.executeRequestInterceptors(query)
          const result = await this.mcpClient.query(interceptedQuery.query, interceptedQuery.params)
          const interceptedResult = await this.executeResponseInterceptors(result)
          results.push(interceptedResult)
        }

        // 提交事务
        await this.mcpClient.query('COMMIT')

        return {
          code: 200,
          message: 'Success',
          data: results,
          timestamp: Date.now(),
        }
      } catch (error) {
        // 回滚事务
        await this.mcpClient.query('ROLLBACK')
        throw error
      }
    } catch (error) {
      // 执行错误拦截器
      const interceptedError = await this.executeErrorInterceptors(error as Error)

      return {
        code: 500,
        message: interceptedError.message,
        data: [],
        timestamp: Date.now(),
      }
    }
  }

  // 执行错误拦截器
  private async executeErrorInterceptors(error: Error): Promise<Error> {
    let result = error
    for (const interceptor of this.interceptors) {
      if (interceptor.onError) {
        result = await interceptor.onError(result)
      }
    }
    return result
  }

  // 执行请求拦截器
  private async executeRequestInterceptors(query: DatabaseQuery): Promise<DatabaseQuery> {
    let result = query
    for (const interceptor of this.interceptors) {
      if (interceptor.onRequest) {
        result = await interceptor.onRequest(result)
      }
    }
    return result
  }

  // 执行响应拦截器
  private async executeResponseInterceptors(result: QueryResult): Promise<QueryResult> {
    let response = result
    for (const interceptor of this.interceptors) {
      if (interceptor.onResponse) {
        response = await interceptor.onResponse(response)
      }
    }
    return response
  }
}
